package com.itheima.tlias.controller;

import com.alibaba.fastjson2.JSONObject;
import com.itheima.tlias.common.result.Result;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Cookie控制器类
 * 处理与cookie相关的HTTP请求
 */
@RestController
@RequestMapping("/cookie")
public class TestCookieController {

    /**
     * 处理保存cookie的GET请求
     * 创建并添加两个cookie（username和password）到HTTP响应中
     *
     * @param response HTTP响应对象，用于添加cookie
     * @return 表示操作成功的结果对象
     */
    @GetMapping("/save")
    public Result saveCookie(HttpServletResponse response){
        // 创建并添加username cookie
        Cookie cookie = new Cookie("username","admin");
        response.addCookie(cookie);
        // 创建并添加password cookie
        Cookie cookie1 = new Cookie("password", "123456");
        response.addCookie(cookie1);
        return Result.success();
    }

    /**
     * 处理获取cookie的GET请求
     * 从HTTP请求中读取所有cookie，并将它们以JSON对象的形式返回
     *
     * @param request HTTP请求对象，用于获取cookie
     * @return 包含所有cookie的JSON对象的结果
     */
    @GetMapping("/get")
    public Result getCookie(HttpServletRequest request){
        // 获取所有cookie
        Cookie[] cookies = request.getCookies();
        JSONObject jsonObject = new JSONObject();
        // 遍历cookie数组，将cookie内容添加到JSON对象中
        for (Cookie cookie : cookies) {
            jsonObject.put(cookie.getName(),cookie.getValue());
        }
        // 返回包含所有cookie的JSON对象，表示操作成功
        return Result.success(jsonObject);
    }
}

